package com.ckx.utils;

import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义Bean拷贝
 */
public class BeanCopyUtil {

    private BeanCopyUtil() {
    }

    /**
     * 拷贝单个对象
     * @param source 源对象
     * @param clzz 目标 Class
     * @param <V>
     * @param <T>
     * @return
     */
    public static <V, T> T copyBean(V source, Class<T> clzz) {
        T instance = null;
        try {
            instance = clzz.newInstance();
            BeanUtils.copyProperties(source, instance);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return instance;
    }

    /**
     * 拷贝集合
     * @param source 源集合
     * @param clazz 目标 Class
     * @param <T>
     * @return 目标集合
     */
    public static <T> List<T> copyBeanList(List<?> source, Class<T> clazz) {

        List<T> collect = source.stream().map(obj -> {
            T instance = null;
            try {
                instance = clazz.newInstance();
                BeanUtils.copyProperties(obj, instance);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return instance;
        }).collect(Collectors.toList());
        return collect;
    }

}
